import 'package:flutter/material.dart';
import 'package:icooker/configs/mock_datas.dart';
import 'package:icooker/model/reommend_data.dart';
import 'package:flutter_ijkplayer/flutter_ijkplayer.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

/// 全屏的视频播放器
/// 基于: flutter_ijkplayer
/// https://pub.flutter-io.cn/packages/flutter_ijkplayer
/// 参考代码:https://github.com/CaiJingLong/flutter_ijkplayer/blob/master/example/lib/page/auto_full_screen.dart
class FlutterIJKFullscreenPlayerView extends StatefulWidget {
  VideoInfoData videoInfo;

  FlutterIJKFullscreenPlayerView(this.videoInfo, {Key? key}) : super(key: key);

  @override
  _FlutterIJKFullscreenPlayerViewState createState() =>
      _FlutterIJKFullscreenPlayerViewState();
}

class _FlutterIJKFullscreenPlayerViewState
    extends State<FlutterIJKFullscreenPlayerView> {
  IjkMediaController controller = IjkMediaController();
  final key = GlobalKey<DefaultIJKControllerWidgetState>();

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: FutureBuilder(
        future: setDataSource(),
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            print("snapshot- data: ${snapshot.data}");
            return Container(
              child: buildIjkPlayer(),
            );
          } else {
            return Center(
              child: CircularProgressIndicator(),
            );
          }
        },
      ),
    );
  }

  Center buildCenter() {
    return Center(
      child: AspectRatio(
        // aspectRatio: controller.videoInfo.ratio,
        aspectRatio: 1 / 1,
        child: buildIjkPlayer(),
      ),
    );
  }

  IjkPlayer buildIjkPlayer() {
    return IjkPlayer(
      mediaController: controller,
      controllerWidgetBuilder: (ctl) => DefaultIJKControllerWidget(
        controller: ctl,
        key: key,
      ),
    );
  }

  Future setDataSource() async {
    await controller.setNetworkDataSource(widget.videoInfo.video!.vendorVideo!,
        autoPlay: true);

    controller.playFinishStream.listen((event) {
      print("IJK controller-event: $event");
    }, onError: () {
      print("IJK 出现错误了");
    }, onDone: () {
      print("IJK 播放器准备完成了");
    }, cancelOnError: true);

    // controller.
    // key.currentState!.fullScreen();
    return true;
  }
}
